var express = require("express");
const app = express();
const verifyToken = require("../utils/verifyToken");
var router = express.Router();
const moment = require("moment");
const sqlconfig = require("../mysql/config");
const { createResponse } = require("../utils/responseHelper");
const multer = require("multer");
const path = require("path");

// 配置 multer 来处理文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage: storage });

/**
 * 获取文章列表
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回文章列表的 Promise
 */
router.get("/getArticleList", async (req, res) => {
  try {
    const sql = `
      SELECT 
        id, 
        title, 
        type, 
        keywords,
        summary,
        content_type AS contentType,
        images,
        create_time AS createTime,
        update_time AS updateTime,
        status,
        create_user_name AS createUserName,
        update_user_name AS updateUserName
      FROM articles
      ORDER BY create_time DESC
    `;
    sqlconfig.query(sql, (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      const formattedResult = result.map((article) => ({
        ...article,
        images: JSON.parse(article.images || "[]"),
        createTime: moment(article.createTime).format("YYYY-MM-DD HH:mm:ss"),
        updateTime: moment(article.updateTime).format("YYYY-MM-DD HH:mm:ss"),
      }));
      createResponse(res, "SUCCESS", formattedResult, "获取文章列表成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * 添加新文章
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回添加文章操作的 Promise
 */
router.post("/addArticle", verifyToken, async (req, res) => {
  try {
    const { title, type, keywords, summary, content, contentType, images } = req.body;
    const timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
    const userId = req.user.userId;
    const userName = req.user.userName;
    
    const sql = `
      INSERT INTO articles 
      (title, type, keywords, summary, content, content_type, images, create_time, update_time, status, create_user_id, create_user_name, update_user_id, update_user_name) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)
    `;
    sqlconfig.query(
      sql,
      [
        title,
        type,
        keywords,
        summary,
        content,
        contentType,
        JSON.stringify(images),
        timestamp,
        timestamp,
        userId,
        userName,
        userId,
        userName
      ],
      (err, result) => {
        if (err) {
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }
        createResponse(res, "SUCCESS", null, "添加文章成功");
      }
    );
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * 更新文章
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回更新文章操作的 Promise
 */
router.put("/updateArticle/:id", verifyToken, async (req, res) => {
  try {
    const { id } = req.params;
    const {
      title,
      type,
      keywords,
      summary,
      content,
      contentType,
      images,
      status,
    } = req.body;
    const timestamp = moment().format("YYYY-MM-DD HH:mm:ss");
    const userId = req.user.userId;
    const userName = req.user.userName;
    console.log(req.user)
    const sql = `
      UPDATE articles 
      SET title = ?, type = ?, keywords = ?, summary = ?, content = ?, content_type = ?, images = ?, update_time = ?, status = ?, update_user_id = ?, update_user_name = ?
      WHERE id = ?
    `;
    sqlconfig.query(
      sql,
      [
        title,
        type,
        keywords,
        summary,
        content,
        contentType,
        JSON.stringify(images),
        timestamp,
        status,
        userId,
        userName,
        id
      ],
      (err, result) => {
        if (err) {
          console.log(666,err)
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }
        if (result.affectedRows === 0) {
          console.log(777)
          return createResponse(res, "SERVER_ERROR", null, "文章不存在");
        }
        createResponse(res, "SUCCESS", null, "更新文章成功");
      }
    );
  } catch (error) {
    console.log(error)
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * 删除文章
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回删除文章操作的 Promise
 */
router.delete("/deleteArticle/:id", verifyToken, async (req, res) => {
  try {
    const { id } = req.params;
    const sql = "DELETE FROM articles WHERE id = ?";
    sqlconfig.query(sql, [id], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.affectedRows === 0) {
        return createResponse(res, "SERVER_ERROR", null, "文章不存在");
      }
      createResponse(res, "SUCCESS", null, "删除文章成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * 获取文章内容
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回获取文章内容操作的 Promise
 */
router.get("/getArticleContent/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const sql = "SELECT * FROM articles WHERE id = ?";
    sqlconfig.query(sql, [id], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.length === 0) {
        return createResponse(res, "SERVER_ERROR", null, "文章不存在");
      }
      const rawArticle = result[0];

      const article = {
        id: rawArticle.id,
        title: rawArticle.title,
        type: rawArticle.type,
        keywords: rawArticle.keywords,
        summary: rawArticle.summary,
        content: rawArticle.content,
        contentType: rawArticle.content_type,
        images: JSON.parse(rawArticle.images || "[]"),
        createTime: moment(rawArticle.create_time).format("YYYY-MM-DD HH:mm:ss"),
        updateTime: moment(rawArticle.update_time).format("YYYY-MM-DD HH:mm:ss"),
        status: rawArticle.status,
        createUserName: rawArticle.create_user_name,
        updateUserName: rawArticle.update_user_name
      };

      createResponse(res, "SUCCESS", article, "获取文章内容成功");
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

/**
 * 上传图片
 * @param {Object} req - Express 请求对象
 * @param {Object} res - Express 响应对象
 * @returns {Promise} 返回上传图片操作的 Promise
 */
router.post("/uploadImage", verifyToken, upload.single("image"), (req, res) => {
  if (!req.file) {
    console.error("No file uploaded");
    return createResponse(res, "SERVER_ERROR", null, "No file uploaded");
  }
  console.log("File uploaded:", req.file);
  const imageUrl = `/uploads/${req.file.filename}`;
  createResponse(
    res,
    "SUCCESS",
    { url: imageUrl },
    "Image uploaded successfully"
  );
});

module.exports = router;